"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const child_process_1 = require("child_process");
const path_1 = __importDefault(require("path"));
const multer_1 = __importDefault(require("multer"));
const fileDB_1 = require("../db/fileDB");
const os_1 = __importDefault(require("os"));
const ws_1 = __importDefault(require("ws"));
const router = (0, express_1.Router)();
// WebSocket 客户端
let wsClient = null;
// 连接到 WebSocket 服务器
function connectWebSocket() {
    return new Promise((resolve, reject) => {
        try {
            const ws = new ws_1.default('ws://127.0.0.1:30002');
            ws.on('open', () => {
                console.log('WebSocket 连接已建立');
                resolve(ws);
            });
            ws.on('error', (error) => {
                console.error('WebSocket 连接错误:', error);
                reject(error);
            });
            ws.on('close', () => {
                console.log('WebSocket 连接已关闭');
                wsClient = null;
            });
        }
        catch (error) {
            reject(error);
        }
    });
}
// 发送消息到 WebSocket
function sendToWebSocket(message) {
    if (wsClient && wsClient.readyState === ws_1.default.OPEN) {
        try {
            wsClient.send(JSON.stringify({
                type: 'python_output',
                timestamp: new Date().toISOString(),
                message: message
            }));
        }
        catch (error) {
            console.error('发送 WebSocket 消息失败:', error);
        }
    }
    else {
        console.warn('WebSocket 未连接，尝试重新连接...');
        // 尝试重新连接
        connectWebSocket().then(ws => {
            wsClient = ws;
            sendToWebSocket(message);
        }).catch(error => {
            console.error('重新连接 WebSocket 失败:', error);
        });
    }
}
// 获取系统桌面路径
function getDesktopPath() {
    const platform = process.platform;
    if (platform === 'win32') {
        // Windows 系统
        return path_1.default.join(process.env.USERPROFILE || '', 'Desktop');
    }
    else if (platform === 'linux') {
        // Linux 系统
        return path_1.default.join(os_1.default.homedir(), '桌面');
    }
    else if (platform === 'darwin') {
        // macOS 系统
        return path_1.default.join(os_1.default.homedir(), 'Desktop');
    }
    else {
        throw new Error('不支持的操作系统');
    }
}
// 配置 multer 存储
const storage = multer_1.default.diskStorage({
    destination: function (req, file, cb) {
        try {
            const desktopPath = getDesktopPath();
            cb(null, desktopPath);
        }
        catch (error) {
            cb(error, '');
        }
    },
    filename: function (req, file, cb) {
        // 保留原始文件名
        cb(null, file.originalname);
    }
});
// 文件过滤器
const fileFilter = (req, file, cb) => {
    // 只接受视频文件
    if (file.mimetype.startsWith('video/')) {
        cb(null, true);
    }
    else {
        cb(new Error('只允许上传视频文件'));
    }
};
// 配置 multer
const upload = (0, multer_1.default)({
    storage: storage,
    fileFilter: fileFilter,
    limits: {
        fileSize: 10 * 1024 * 1024 * 1024, // 10GB
        fieldSize: 10 * 1024 * 1024 * 1024 // 10GB
    }
});
// 上传视频路由
router.post('/upload', upload.single('file'), (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({
                success: false,
                message: '没有上传文件'
            });
        }
        // 使用数据库模块添加记录
        const record = fileDB_1.fileDB.addUpload(req.file.originalname, req.file.path);
        res.json({
            success: true,
            message: '文件上传成功',
            data: {
                filename: record.filename,
                path: record.path,
                uploadTime: record.uploadTime,
                size: req.file.size
            }
        });
    }
    catch (error) {
        // 处理文件大小超限错误
        if (error instanceof multer_1.default.MulterError) {
            if (error.code === 'LIMIT_FILE_SIZE') {
                return res.status(413).json({
                    success: false,
                    message: '文件大小超过限制',
                    error: '文件大小不能超过10GB'
                });
            }
        }
        res.status(500).json({
            success: false,
            message: '文件上传失败',
            error: error instanceof Error ? error.message : '未知错误'
        });
    }
});
// 开始检测路由
// 保存 Python 进程的引用
let pythonProcess = null;
router.post('/begin', async (req, res) => {
    // 检测站点
    let station = req.body.station;
    // 检测车次
    let trainNumber = req.body.trainNumber;
    // 获取最新的上传记录
    const latestUpload = fileDB_1.fileDB.getLatestUpload();
    if (!latestUpload) {
        return res.status(400).json({
            success: false,
            message: '没有找到上传的视频文件，请先上传视频'
        });
    }
    // 检测视频路径
    let videoPath = latestUpload.path;
    try {
        // 如果已经有进程在运行，先停止它
        if (pythonProcess) {
            pythonProcess.kill();
            pythonProcess = null;
        }
        // 建立 WebSocket 连接
        try {
            wsClient = await connectWebSocket();
            sendToWebSocket('检测进程启动中...');
        }
        catch (error) {
            console.error('WebSocket 连接失败:', error);
            // 即使 WebSocket 连接失败，也继续执行 Python 脚本
        }
        // 获取桌面路径
        const desktopPath = getDesktopPath();
        const pythonScriptPath = path_1.default.join(desktopPath, 'color2mp4WebSocket_0610.py');
        console.log('Operating System:', process.platform);
        console.log('Desktop path:', desktopPath);
        console.log('Video path:', videoPath);
        console.log('Python script path:', pythonScriptPath);
        // 启动 Python 进程，传入参数
        pythonProcess = (0, child_process_1.spawn)('python', [
            pythonScriptPath,
            '--video_path', videoPath,
            '--start_position', station,
            '--train_num', trainNumber
        ]);
        // 处理 Python 脚本的输出
        if (pythonProcess.stdout) {
            pythonProcess.stdout.on('data', (data) => {
                console.log(`Python 输出: ${data.toString('utf-8')}`);
                sendToWebSocket(`Python 输出: ${data.toString('utf-8')}`);
            });
        }
        // 处理 Python 脚本的错误
        if (pythonProcess.stderr) {
            pythonProcess.stderr.on('data', (data) => {
                console.error(`Python 错误: ${data.toString('utf-8')}`);
                sendToWebSocket(`Python 错误: ${data.toString('utf-8')}`);
            });
        }
        // 等待进程启动成功
        pythonProcess.on('spawn', () => {
            // 示例响应
            res.json({
                success: true,
                message: '检测已开始',
                data: {
                    startTime: new Date().toISOString(),
                    pythonScriptPath: pythonScriptPath,
                    videoPath: videoPath,
                    station: station,
                    trainNumber: trainNumber
                }
            });
        });
        // 处理 Python 进程的关闭
        pythonProcess.on('close', (code) => {
            console.log(`Python 进程退出，退出码: ${code}`);
            sendToWebSocket(`Python 进程退出，退出码: ${code}`);
            pythonProcess = null;
            // 关闭 WebSocket 连接
            if (wsClient) {
                wsClient.close();
                wsClient = null;
            }
        });
        // 处理启动错误
        pythonProcess.on('error', (error) => {
            console.error('启动 Python 进程失败:', error);
            sendToWebSocket(`启动 Python 进程失败: ${error.message}`);
            res.status(500).json({
                success: false,
                message: '启动检测失败',
                error: error.message
            });
        });
    }
    catch (error) {
        res.status(500).json({
            success: false,
            message: '启动检测失败',
            error: error instanceof Error ? error.message : '未知错误'
        });
    }
});
// 停止检测路由
router.post('/stop', (req, res) => {
    try {
        if (pythonProcess) {
            sendToWebSocket('正在停止检测进程...');
            // 在 Windows 上使用 taskkill 强制结束进程
            if (process.platform === 'win32' && pythonProcess.pid) {
                (0, child_process_1.spawn)('taskkill', ['/pid', pythonProcess.pid.toString(), '/f', '/t']);
            }
            else {
                // 在 Unix 系统上使用 kill 命令
                pythonProcess.kill('SIGTERM');
            }
            pythonProcess = null;
            sendToWebSocket('检测进程已停止');
            res.json({
                success: true,
                message: '检测已停止',
                data: {
                    stopTime: new Date().toISOString()
                }
            });
        }
        else {
            res.json({
                success: false,
                message: '没有正在运行的检测进程'
            });
        }
    }
    catch (error) {
        sendToWebSocket(`停止检测失败: ${error instanceof Error ? error.message : '未知错误'}`);
        res.status(500).json({
            success: false,
            message: '停止检测失败',
            error: error instanceof Error ? error.message : '未知错误'
        });
    }
});
exports.default = router;
